/**
 * NumberRange 配合form组件使用
 * @Author: linzy
 * @Date: 2022-10-09
 * @function NumberRange
 * @param {array} placeholder=["下限","上限"] - 占位符
 * @param {array} value=[undefined,undefined] - 初始值
 * @param {*} ... antd InputNumber组件属性
 * @example
 * <NumberRange />
 */
import { InputNumber, Icon } from "antd";
import { setDefaultAttrs } from "@/hooks/tools";
import "./style.css";

export default (props = {}) => {
  setDefaultAttrs(props, {
    placeholder: ["下限", "上限"],
    value: [undefined, undefined],
  });
  let { value, onChange, ...restProps } = props;
  function formChange(from, val) {
    if (from === 0) {
      if (val < 0 || val > value[1]) {
        value[0] = undefined;
      } else {
        value[from] = val;
      }
    }
    if (from === 1) {
      if (val < 0 || val < value[0]) {
        value[1] = undefined;
      } else {
        value[from] = val;
      }
    }
    onChange && onChange(value);
  }
  return (
    <div className="numberRange ant-input-number">
      <InputNumber
        value={value[0]}
        {...restProps}
        placeholder={props.placeholder[0]}
        onChange={(val) => {
          formChange(0, val);
        }}
        onPressEnter={(val) => {
          formChange(0, val);
        }}
      />
      <div
        className="close_icon_box"
        style={{ visibility: value[0] !== undefined ? "visible" : "hidden" }}
      >
        {props.allowClear && (
          <Icon
            type="close-circle"
            theme="filled"
            className="ant-input-clear-icon close_icon"
            onClick={() => {
              value[0] = undefined;
              onChange && onChange(value);
            }}
          />
        )}
      </div>
      <span className="numberRange-partition">~</span>
      <InputNumber
        value={value[1]}
        {...restProps}
        placeholder={props.placeholder[1]}
        onChange={(val) => {
          formChange(1, val);
        }}
        onPressEnter={(val) => {
          formChange(1, val);
        }}
      />
      <div
        className="close_icon_box"
        style={{ visibility: value[1] !== undefined ? "visible" : "hidden" }}
      >
        {props.allowClear && (
          <Icon
            type="close-circle"
            theme="filled"
            className="ant-input-clear-icon close_icon"
            onClick={() => {
              value[1] = undefined;
              onChange && onChange(value);
            }}
          />
        )}
      </div>
    </div>
  );
};
